package com.alibaba.yinan.domain.task.service.lifecycle;

import com.alibaba.yinan.domain.task.enums.TaskEvent;
import com.alibaba.yinan.domain.task.enums.TaskStatus;
import jakarta.annotation.Resource;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Component;


/**
 * @ClassName TaskStateMachineHandler
 * @Author mengke
 * @create 2025/8/3 20:31
 * @Description
 */
@Component
public class TaskStateMachineHandler {

    @Resource
    private StateMachine<TaskStatus, TaskEvent> taskStateMachine;

    public TaskStatus fireEvent(TaskStatus currentStatus, TaskEvent event) {
        taskStateMachine.stop();

        taskStateMachine.getStateMachineAccessor()
                .doWithAllRegions(access -> {
                    access.resetStateMachine(
                            new DefaultStateMachineContext<>(currentStatus, null, null, null));
                });

        taskStateMachine.start();
        boolean success = taskStateMachine.sendEvent(event);

        if (!success) {
            throw new IllegalStateException("状态机事件发送失败：" + event);
        }

        return taskStateMachine.getState().getId();
    }
}
